/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BUS;

import BUSObject.CartItem;
import DAL.DABasic;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author HOANG ANH
 */
public class BUSOrder {

    private DABasic daBasic;

    public BUSOrder() {
        daBasic = new DABasic();
    }
    
    public int NewOrder(int UserID, Iterator<CartItem> cartList){
        try {
            CallableStatement order_Insert = daBasic.PrepareCall("{Call Order_Insert(?,?)}");
            order_Insert.setInt(1, UserID);
            order_Insert.registerOutParameter(2, Types.INTEGER);
            order_Insert = daBasic.ExecuteOutput(order_Insert);
            
            int orderID = order_Insert.getInt(2);
            daBasic.Close(order_Insert);
            
            PreparedStatement orderDetail_Insert = daBasic.PreparedStatement("INSERT INTO OrderDetails (ProductID, OrderID, Quantity) VALUES  (?,?,?)");
            for (Iterator<CartItem> it = cartList; it.hasNext();) {
                CartItem item = it.next();
                
                orderDetail_Insert.setInt(1, item.getID());
                orderDetail_Insert.setInt(2, orderID);
                orderDetail_Insert.setInt(3, item.getQuantity());
                orderDetail_Insert.addBatch();
                
            }
            daBasic.ExecuteBatch(orderDetail_Insert);
            
            return orderID;
        } catch (SQLException ex) {
            Logger.getLogger(BUSOrder.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }
    }
}
